package com.gwt.tirso.gymkhana.client;

import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ContestStep4 implements EntryPoint {
	
	private Label correctLb = new Label("¡Correcto!");
	private Label clueLb = new Label("Pista");
	private Label clue = new Label();
	private Label codeLb = new Label("Inserta el codigo, cuando lo encuentres, aqui:");
	private TextBox codeBox = new TextBox();
	private Button acceptBt = new Button("Aceptar");
	private VerticalPanel mainPanel = new VerticalPanel();
	private Question q = new Question();
	private Label errorLabel = new Label("");

	private String code;
	private Gymkhana gymkhana;
	private int questN;
	private List<Question> lq;

	

	@Override
	public void onModuleLoad() {
		
		loadContestStep4();
		
	}
	
	public static int randomNumber(int max,int min){
		return (int) Math.floor(Math.random()*(max-min+1)+min);
		}

	private void loadContestStep4() {

		mainPanel.add(correctLb);
		
		mainPanel.add(clueLb);
		
		/*
		//Clue text treatment, here, we take the next question randomly 
		int random = Random.nextInt();
		random = random * random;
		//this if is to fix an arrayOutOfBoundsException
		if(lq.size() > 1){
			int aux = random % lq.size()+1;
			q = lq.get(aux);
		}else{
			q = lq.get(0);
		}*/
		
		int random = randomNumber(0, lq.size()-1);
		q = lq.get(random);
		
		clue.setText(q.getClueText());
		
		mainPanel.add(clue);
		
		mainPanel.add(codeLb);
		mainPanel.add(codeBox);
		code = q.getCode();
		
		acceptBt.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				if(codeBox.getText().equals(code)){
					
					loadStep3();
					
				}else{
					errorLabel.setText("No es correcto, intentalo de nuevo. Asegurate de que este bien escrito.");
					codeBox.setText("");
					codeBox.setFocus(true);
				}
			}
		});
		
		mainPanel.add(acceptBt);
		mainPanel.add(errorLabel);
		
		mainPanel.addStyleName("contestNext");		
		RootPanel.get("contest").add(mainPanel);
	}

	protected void loadStep3() {
		ContestStep3 c3 = new ContestStep3(gymkhana, lq, questN, code);
		c3.onModuleLoad();
		RootPanel.get("contest").remove(mainPanel);		
	}
	
	public ContestStep4(Gymkhana g, int qN, List<Question> lq) {
		gymkhana = g;
		questN = qN;
		this.lq = lq;
	}

}
